﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;

namespace OOO.Scene
{
	public class Animation : GameEntity
	{
		private FloatTween _tween = null;
		private Bitmap[] _frames = null;
		private float _duration = 0;
		private int _currentFrameIndex = 0;

		public event Action AnimationPauseEvent;
		public event Action AnimationStopEvent;
		public event Action<int> AnimationFrameChangeEvent;

		public Animation(Canvas c, Bitmap[] frames)
		{
			_tween = new FloatTween();

			_frames = frames;
			_canvas = c;

			PointF zero = new PointF(0, 0);
		}

		public void Start(float duration, float x, float y)
		{
			_x = x;
			_y = y;
			_duration = duration;

			_tween.Start(0, _frames.Length - 1, _duration, ScaleFuncs.Linear); 
		}

		public void Pause()
		{
			_tween.Pause();

			if (AnimationPauseEvent != null)
				AnimationPauseEvent();
		}

		public void Stop()
		{
			_tween.Stop();

			if (AnimationStopEvent != null)
				AnimationStopEvent();
		}

		public bool IsRunning
		{
			get
			{
				return _tween.State == TweenState.Running;
			}
		}

		public override void Update(int elapsedMS)
		{
			_tween.Update(elapsedMS);

			int index = (int)_tween.CurrentValue;

			if (index != _currentFrameIndex && AnimationFrameChangeEvent != null)
			{
				AnimationFrameChangeEvent(index);
			}

			_currentFrameIndex = index;

			if (_tween.State == TweenState.Stopped && AnimationStopEvent != null)
				AnimationStopEvent();

		}

		public override void Render()
		{
			_texture = _frames[_currentFrameIndex];
			_width = _texture.Width;
			_height = _texture.Height;

			_canvas.DrawBitmap(_texture, new Rectangle((int)(_x), (int)(_y), _width, _height));
		}
	}
}
